package io.renren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.util.StrUtil;
import dm.jdbc.util.DateUtil;
import dm.jdbc.util.StringUtil;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.dao.*;
import io.renren.dto.AutorepairmDTO;
import io.renren.dto.AutorescueitemsdDTO;
import io.renren.dto.BusinessmDTO;
import io.renren.dto.ServerListQueryDto;
import io.renren.entity.*;
import io.renren.service.*;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author Sen 524227263@qq.com
 * @since 1.0.0 2024-05-29
 */
@Service
public class AutorescueitemsdServiceImpl extends CrudServiceImpl<AutorescueitemsdDao, AutorescueitemsdEntity, AutorescueitemsdDTO> implements AutorescueitemsdService {

    @Autowired
    private AutoDao autoDao;
    @Autowired
    private AutorepairmDao autorepairmDao;
    @Autowired
    private AutodecoratemDao autorecoratemDao;
    @Autowired
    private AutowashmDao autashmDao;
    @Autowired
    private AutorescuemDao autorescuemDao;
    @Autowired
    private AgencyinsuranceregmDao agencyinsuranceregmDao;
    @Autowired
    private JoinmembermDao joinmembermDao;
    @Autowired
    private AutoservicemDao autoservicemDao;
    @Autowired
    private ChatgroupDao chatgroupDao;
    @Autowired
    private UcmlOrganizeDao ucmlOrganizeDao;
    @Autowired
    private UcmlContactDao ucmlContactDao;
    @Autowired
    private BusinessmDao businessmDao;
    @Autowired
    private AutodecorateitemsdService autodecorateitemsdService;
    @Autowired
    private ProjectmService projectmService;
    @Autowired
    private AutodecorategoodsdService autodecorategoodsdService;
    @Autowired
    private GoodsmService goodsmService;
    @Autowired
    private AutowashmService autowashmService;
    @Autowired
    private AgencyinsurancedService agencyinsurancedService;
    @Autowired
    private JoinmembermService joinmembermService;
    @Autowired
    private GiftpackagerulemService giftpackagerulemService;
    @Autowired
    private CarserviceitemsdService carserviceitemsdService;

    @Override
    public QueryWrapper<AutorescueitemsdEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<AutorescueitemsdEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public Map<String, Object> serviceList(String traderMOID, ServerListQueryDto dto) {
        Map<String, Object> result = new HashMap<>();
        List<String> AutoOIDArr = new ArrayList<>();
        if (StringUtil.isNotEmpty(dto.getAutoOID())) {
            AutoOIDArr.add(dto.getAutoOID());
        } else {
            QueryWrapper<AutoEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("AutoOID");
            queryWrapper.eq("TraderM_FK", traderMOID);
            List<AutoEntity> autoEntities = autoDao.selectList(queryWrapper);
            if (autoEntities.size() > 0) {
                AutoOIDArr = autoEntities.stream().map(AutoEntity::getAutooid).collect(Collectors.toList());
            } else {
                AutoOIDArr.add("00000000-0000-0000-0000-000000000000");
            }
        }
        // 服务单状态
        if (StringUtil.isEmpty(dto.getAutoRepairStateName())) {
            dto.setAutoRepairStateName("服务中");
        }
        String whereSql = "";
        if (AutoOIDArr.size() > 0) {
            String statusArr = "";
            for (String AutoOID : AutoOIDArr) {
                statusArr += "'" + AutoOID.trim() + "',";
            }
            if (statusArr.length() > 0) {
                statusArr = statusArr.substring(0, statusArr.length() - 1);
            }
            whereSql += "Auto_FK in (" + statusArr + ")";
        }
        String statusSql = "";
        if (dto.getAutoRepairStateName().equals("服务中")) {
            statusSql = " AutoRepairStateName != '待结算' and AutoRepairStateName != '结算中' and AutoRepairStateName != '挂账' and AutoRepairStateName != '完成' and AutoRepairStateName != '已评价' ";
        } else if (dto.getAutoRepairStateName().equals("待支付")) {
            statusSql = " (AutoRepairStateName='待结算' or AutoRepairStateName='结算中') ";
        } else if (dto.getAutoRepairStateName().equals("待评价")) {
            statusSql = " AutoRepairStateName='完成' ";
        } else if (dto.getAutoRepairStateName().equals("已评价")) {
            statusSql = " AutoRepairStateName='已评价' ";
        } else if (dto.getAutoRepairStateName().equals("已完成")) {
            statusSql = " (AutoRepairStateName='已评价' or AutoRepairStateName='完成') ";
        }

        if (StringUtil.isNotEmpty(whereSql)) {
            whereSql = " where " + whereSql + " and " + statusSql + " ";
        } else {
            whereSql = " where " + statusSql + " ";
        }


        Integer page = dto.getPage() - 1;
        Integer perPage = dto.getPerPage() * dto.getPage();
        List<Map<String, Object>> list = baseDao.selectMapBySql(whereSql, page, perPage);
        Integer totalCount = baseDao.selectCountBySql(whereSql);
        for (Map<String, Object> map : list) {
            map.put("BillDate", DateUtils.formatDate((Date) map.get("BillDate"), "yyyy-MM-dd"));
            AutoEntity autoEntity = autoDao.selectOne(new QueryWrapper<AutoEntity>().eq("AutoOID", map.get("Auto_FK")));
            if (autoEntity != null) {
                map.put("AutoNo", autoEntity.getAutono());
                ChatgroupEntity chatgroupInfo = chatgroupDao.selectOne(new QueryWrapper<ChatgroupEntity>().eq("IMGroupID", autoEntity.getAutoframenum()));
                if (chatgroupInfo != null) {
                    map.put("groupId", chatgroupInfo.getImgroupid());
                } else {
                    map.put("groupId", "");
                }

                UcmlOrganizeEntity ucmlOrganizeEntity = ucmlOrganizeDao.selectOne(new QueryWrapper<UcmlOrganizeEntity>()
                        .eq("UCML_OrganizeOID", map.get("Org_FK")));
                if (ucmlOrganizeEntity != null) {
                    map.put("orgName", ucmlOrganizeEntity.getOrgname());
                } else {
                    map.put("orgName", "");
                }
                UcmlContactEntity ucmlContactEntity = ucmlContactDao.selectOne(new QueryWrapper<UcmlContactEntity>()
                        .eq("UCML_CONTACTOID", map.get("UCML_CONTACT_FK")));
                if (ucmlContactEntity != null) {
                    map.put("PersonName", ucmlContactEntity.getPersonname());
                } else {
                    map.put("PersonName", "");
                }
                map.put("billTYpe", "");
                String BillCode = map.get("BillCode") == null ? "" : map.get("BillCode").toString();
                if (StringUtil.isNotEmpty(BillCode)) {
                    String[] billCodeArr = BillCode.split("-");
                    if (billCodeArr.length > 0) {
                        map.put("billTYpe", billCodeArr[0]);
                    }
                }
                BusinessmEntity businessmEntity = businessmDao.selectOne(new QueryWrapper<BusinessmEntity>().eq("SourceBillOID", map.get("Fk")));
                if (businessmEntity != null) {
                    map.put("billOID", businessmEntity.getSettlementmFk());
                } else {
                    map.put("billOID", "");
                }
                if ("车辆美容".equals(map.get("typeName"))) {
                    List<AutodecorateitemsdEntity> autodecorateitemsdList = autodecorateitemsdService.findListByAutoDecorateMFK(map.get("Fk").toString());
                    List<Map<String, Object>> projectList = new ArrayList<>();

                    for (AutodecorateitemsdEntity info : autodecorateitemsdList) {
                        ProjectmEntity projectmEntity = projectmService.findOneByProjectMOID(info.getProjectmFk());
                        if (projectmEntity != null) {
                            Map<String, Object> projectMap = new HashMap<>();
                            projectMap.put("projectName", projectmEntity.getName());
                            projectMap.put("BusinessAmount", info.getBusinessprice());
                            projectMap.put("Amount", info.getAmount());
                            projectList.add(projectMap);
                        }
                    }
                    map.put("projectList", projectList);

                    List<String> goodsMOIDs = autodecorategoodsdService.findGoodsMOIDByAutoDecorateMFk(map.get("Fk").toString());
                    if (goodsMOIDs.size() > 0) {
                        String goodsName = goodsmService.findNameByGoodsMOIDs(goodsMOIDs);
                        map.put("goodsName", goodsName);
                    } else {
                        map.put("goodsName", "");
                    }
                } else if ("车辆洗车".equals(map.get("typeName"))) {
                    List<AutowashmEntity> autowashmList = autowashmService.findListByAutoWashMOID(map.get("Fk").toString());
                    List<Map<String, Object>> projectList = new ArrayList<>();
                    for (AutowashmEntity info : autowashmList) {
                        ProjectmEntity projectmEntity = projectmService.findOneByProjectMOID(info.getProjectmFk());
                        if (projectmEntity != null) {
                            Map<String, Object> projectMap = new HashMap<>();
                            projectMap.put("projectName", projectmEntity.getName());
                            projectMap.put("BusinessAmount", info.getTotalamount());
                            projectMap.put("Amount", info.getAmount());
                            projectMap.put("DiscountAmount", info.getDiscountamount());
                            projectList.add(projectMap);
                        }
                    }
                    map.put("projectList", projectList);
                    map.put("goodsName", "");
                } else if ("车辆救援".equals(map.get("typeName"))) {
                    List<AutorescueitemsdEntity> autorescueitemsdList = findListByAutoRescueMFK(map.get("Fk").toString());
                    List<Map<String, Object>> projectList = new ArrayList<>();
                    for (AutorescueitemsdEntity info : autorescueitemsdList) {
                        ProjectmEntity projectmEntity = projectmService.findOneByProjectMOID(info.getProjectmFk());
                        if (projectmEntity != null) {
                            Map<String, Object> projectMap = new HashMap<>();
                            projectMap.put("projectName", projectmEntity.getName());
                            projectMap.put("BusinessAmount", info.getBusinessamount());
                            projectMap.put("Amount", info.getAmount());
                            projectMap.put("DiscountAmount", info.getDiscountamount());
                            projectList.add(projectMap);
                        }
                    }
                    map.put("projectList", projectList);
                    List<String> goodsMOIDs = findGoodsMOIDByAutoRescueMFk(map.get("Fk").toString());
                    if (goodsMOIDs.size() > 0) {
                        String goodsName = goodsmService.findNameByGoodsMOIDs(goodsMOIDs);
                        map.put("goodsName", goodsName);
                    } else {
                        map.put("goodsName", "");
                    }
                } else if ("保险".equals(map.get("typeName"))) {
                    List<AgencyinsurancedEntity> agencyinsurancedList = agencyinsurancedService.findListByAgencyInsuranceRegMFK(map.get("Fk").toString());
                    List<Map<String, Object>> projectList = new ArrayList<>();
                    for (AgencyinsurancedEntity info : agencyinsurancedList) {
                        String projectmName = projectmService.findNameForInsuranceOID(info.getInsuranceFk());
                        Map<String, Object> projectMap = new HashMap<>();
                        projectMap.put("projectName", projectmName);
                        projectMap.put("BusinessAmount", info.getInsuranceamount());
                        projectMap.put("InsuranceAmount", info.getInsuranceamount());
                        projectMap.put("DiscountAmount", info.getDiscountrate());
                        projectMap.put("Amount", info.getAmount());
                        projectList.add(projectMap);
                    }
                    map.put("projectList", projectList);
                    map.put("goodsName", "");
                } else if ("车辆VIP".equals(map.get("typeName"))) {
                    List<JoinmembermEntity> JoinmembermList = joinmembermService.findListByJoinMemberMOID(map.get("Fk").toString());
                    List<Map<String, Object>> projectList = new ArrayList<>();
                    for (JoinmembermEntity info : JoinmembermList) {
                        GiftpackagerulemEntity projectmName = giftpackagerulemService.findNameByGiftPackageRuleMOID(info.getGiftpackagerulemFk());
                        Map<String, Object> projectMap = new HashMap<>();
                        projectMap.put("projectName", projectmName != null ? projectmName.getGiftpackagename() : "");
                        projectMap.put("DiscountAmount", 0);
                        projectMap.put("BusinessAmount", 0);
                        projectMap.put("Amount", info.getMembershipamount());
                        projectList.add(projectMap);
                    }
                    map.put("projectList", projectList);
                    map.put("goodsName", "");
                } else if ("车务".equals(map.get("typeName"))) {
                    List<Map<String, Object>> carserviceitemsdList = carserviceitemsdService.findListByAutoServiceMFK(map.get("Fk").toString());
                    List<Map<String, Object>> projectList = new ArrayList<>();
                    for (Map<String, Object> info : carserviceitemsdList) {
                        String projectmName = projectmService.findNameByProjectMOID(info.get("ProjectM_FK").toString());
                        map.put("projectName", projectmName);

                        ProjectmEntity projectmEntity = projectmService.findOneByProjectMOID(info.get("ProjectM_FK").toString());
                        Map<String, Object> projectMap = new HashMap<>();
                        projectMap.put("projectName", projectmEntity != null ? projectmEntity.getName() : "");
                        projectMap.put("BusinessAmount", info.get("BusinessAmount"));
                        projectMap.put("Amount", info.get("Amount"));
                        projectList.add(projectMap);
                    }
                    map.put("projectList", projectList);
                    map.put("goodsName", "");
                } else {
                    List<Map<String, Object>> autorepairitemsdList = projectmService.findListByAutoRepairMFK(map.get("Fk").toString());
                    List<Map<String, Object>> projectList = new ArrayList<>();
                    for (Map<String, Object> info : autorepairitemsdList) {
                        ProjectmEntity projectmEntity = projectmService.findOneByProjectMOID(info.get("ProjectM_FK").toString());
                        Map<String, Object> projectMap = new HashMap<>();
                        projectMap.put("projectName", projectmEntity != null ? projectmEntity.getName() : "");
                        projectMap.put("DiscountAmount", info.get("DiscountAmount"));
                        projectMap.put("BusinessAmount", info.get("BusinessAmount"));
                        projectMap.put("Amount", info.get("Amount"));
                        projectList.add(projectMap);
                    }
                    List<String> goodsMOIDs = findGoodsMOIDForAutorepairpickingd(map.get("Fk").toString());
                    if (goodsMOIDs.size() > 0) {
                        map.put("goodsName", goodsmService.findNameByGoodsMOIDs(goodsMOIDs));
                    } else {
                        map.put("goodsName", "");
                    }
                    map.put("projectList", projectList);
                }

            }
        }
        result.put("data", list);
        result.put("total", totalCount);
        result.put("per_page", perPage);
        result.put("current_page", page);
        result.put("last_page", totalCount / perPage);


        return result;
    }

    private List<String> findGoodsMOIDForAutorepairpickingd(String fk) {
        List<Map<String, String>> proList = this.baseDao.findGoodsMOIDForAutorepairpickingd(fk);
        return proList.stream().map(map -> map.get("GoodsM_FK")).collect(Collectors.toList());
    }

    private List<String> findGoodsMOIDByAutoRescueMFk(String fk) {
        List<Map<String, String>> proList = this.baseDao.getProjectListForAutorescuegoodsd(fk);
        List<String> goodsMOIDs = new ArrayList<>();
        for (Map<String, String> info : proList) {
            if (StringUtil.isNotEmpty(info.get("GoodsM_FK"))) {
                goodsMOIDs.add(info.get("GoodsM_FK"));
            }
        }
        return goodsMOIDs;
    }

    private List<AutorescueitemsdEntity> findListByAutoRescueMFK(String fk) {
        List<AutorescueitemsdEntity> proList = this.baseDao.selectList(
                new QueryWrapper<AutorescueitemsdEntity>()
                        .select("ProjectM_FK,Amount,DiscountAmount,BusinessAmount,Price")
                        .eq("AutoRescueM_FK", fk));
        return proList;
    }
}